<?php

namespace app\api\service\event;

use app\api\model\event\Event;
use app\api\model\event\StudyImg;
use app\lib\exception\event\CreatorException;
use think\Db;
use think\Exception;

class EventService
{
    private static $instance;

    public static function getInstance(): EventService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }


    public function distribute($params){        $current_time = date("Y-m-d H:i:s");
        $get_time = date("Y-m-d H:i:s", time() - 60);
        $result = [];
        DB::startTrans();
        $appids = [];
        $count = 0;
        try {
            $app_id__arr_query = Event::where("get_time",'>',$get_time);
            $app_id_arr = $app_id__arr_query
                ->distinct(true)
                ->field('app_id')
                ->select()->toArray();
            $temporary = [];
            foreach ($app_id_arr as $val){
                $temporary[] = $val['app_id'];
            }
            $query = Event::where("status",1)
                ->where("pub_type",1)
                ->where("pub_time", '<',$current_time)
                ->whereNotIn("app_id",$temporary);
            $list = $query->with(['account'])
                ->orderRand()
                ->lock(true)
                ->limit(10)->select();
            if(!$list->isEmpty()){
                $ids = [];
                foreach ($list as $item){
                    if(!in_array($item['app_id'],$appids)){
                        $appids[] = $item['app_id'];
                        $result[] = $item;
                        $ids[] = $item['id'];
                        $count++;
                    }
                }
                if (!empty($ids)){
                    Event::whereIn('id',$ids)->update([
                        'status' => 2,
                        'get_time'=>date("Y-m-d H:i:s"),
                        'update_time'=>date("Y-m-d H:i:s")
                    ]);
                }

            }
             // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
        Db::rollback();
        }
        return $result;
    }


    public function write($params){
        $Event = Event::where('id',$params['id'])->findOrEmpty();
        if (!$Event->isEmpty()){
            if ($Event->status != 3){
                $Event->save($params);
            }
        }
    }


    public function store($attrs){
        $i = 0;
        if(!empty($attrs)) {
            if (!is_array($attrs)) {
                $attrs = \GuzzleHttp\json_decode($attrs, true);
            }
            DB::startTrans();
            try {
                foreach ($attrs as $attr) {
                    $data = Event::where('feed_id', $attr['feed_id'])->findOrEmpty();
                    if (!$data->isEmpty()) {
                        $data->save($attr);
                    }
                    $i++;
                }
                // 提交事务
                Db::commit();
            }catch (Exception $e) {
                $i = 0;
                // 回滚事务
                Db::rollback();
            }


            }
        return $i;
    }

    public function addStudyImg($params){
        $i = 0;
        if(!empty($params)) {
            // 启动事务
            Db::startTrans();
            try {
                $data = [
                    "link"=>$params['link'],
                    "reason"=>$params['reason'],
                    "path_url"=>$params['path_url']??"",
                    "img"=>$params['img']??[],
                    "title"=>$params['title']??""
                ];
                StudyImg::create($data);
                // 提交事务
                Db::commit();
            } catch (Exception $e){
                var_dump($e->getMessage());
                // 回滚事务
                Db::rollback();
                throw new CreatorException([
                    'msg' => $e->getMessage(),
                    'error_code' => 20001
                ]);
            }
        }

        return $i;

    }
}
